/*
 * 工作空间
 */
 
function BiWorksapce() {
	var workspace = this;
	// 空间搜索框
	var searchDiv = $(".tempo-filter-search");
	//NoteBook跳转按钮
	var $notebookSkipButton = $('#notebook-skip-button');
	var $notebookSkipButtonInit = $('#notebook-skip-button-init');
	var $workspaceAddButton = $('#workspace-add-button');
	var $workspaceInitFirstAddButton = $('#workspace-add-button-init-first');
	var $workspaceInitSecondAddButton = $('#workspace-add-button-init-second');
	var workSpaceLength;
	var $nodeItemMenu = $('.node-item-menu');
	var $enterspace = $nodeItemMenu.find('.node-item-menu-enterspace');
	var $inviteuser = $nodeItemMenu.find('.node-item-menu-inviteuser');
	var $defaultspace = $nodeItemMenu.find('.node-item-menu-defaultspace');
	var $defaultWorkspaceImg=$('.workspace-default-workspace');
	var reg = new RegExp(".png$|.PNG$|.jpg$|.JPG$");
	var layout = $(".workspace-container");
	var fType=layout.attr("ftype");
	//权限类型 1:管理权限 2:使用权限  如果为空，则包含1、2
	var PriType = "";
	//上次点击的三种类型，用于防止恶意点击
	var lastType = "";
	var userId = layout.attr("_currentUserId");
	var searchName = "";
	//遮罩
	var process;
	var $zonetabsall  = $("#zonetabsall");
	var $zonetabsmanage  = $("#zonetabsmanage");
	var $zonetabsused  = $("#zonetabsused");
	var syscontextmenu =  $("<ul/>").appendTo($("body")).contextmenu({
		data: [{
			text:TempoUtils.locale("bidesign.workspace_enterspace"),
			id:'space-enterspace',
			icon:'ui-icon tempo-ui-icon tempo-ui-icon-export'
		},{
			text:TempoUtils.locale("bidesign.workspace_defaultspace"),
			id:'space-default',
			icon:'ui-icon tempo-ui-icon tempo-ui-icon-rename'  
		},
		{
			text:TempoUtils.locale("bidesign.workspace_editspace"),
			id:'space-editspace',
			icon:'ui-icon tempo-ui-icon tempo-ui-icon-edit'  
		},
		{
			text:TempoUtils.locale("bidesign.workspace_exit"),
			id:'space-exit',
			icon:'ui-icon tempo-ui-icon tempo-ui-icon-delete'  
		},
		{
			text:TempoUtils.locale("bidesign.workspace_delete"),
			id:'space-delete',
			icon:'ui-icon tempo-ui-icon tempo-ui-icon-delete'  
		}],
		select:function(e,ui){
		  var link = ui.linkEl;
		  var itemId = ui.select.id;
		  switch (itemId) {
			case 'space-exit':
				exitNode(link);
				break;
			case 'space-enterspace':
				enterSpace(link);
				break;
			case 'space-default':
				setDefault(link);
				break;
			case 'space-editspace':
				editspace(link);
				break;
			case 'space-delete':
				deleteNode(link);
				break;
			default:
				break;
			}
		  }
	});
	//个人空间菜单
	var selfsyscontextmenu =  $("<ul/>").appendTo($("body")).contextmenu({
		data: [{
			text:TempoUtils.locale("bidesign.workspace_enterspace"),
			id:'space-enterspace',
			icon:'ui-icon tempo-ui-icon tempo-ui-icon-export'
		},{
			text:TempoUtils.locale("bidesign.workspace_defaultspace"),
			id:'space-default',
			icon:'ui-icon tempo-ui-icon tempo-ui-icon-rename'  
		},
//		{
//			text:TempoUtils.locale("bidesign.workspace_uploadcover"),
//			id:'space-uploadcover',
//			icon:'ui-icon tempo-ui-icon tempo-ui-icon-snapshot'  
//		},
		{
			text:TempoUtils.locale("bidesign.workspace_editmessage"),
			id:'space-editmessage',
			icon:'ui-icon tempo-ui-icon tempo-ui-icon-edit'  
		},
		{
			text:TempoUtils.locale("bidesign.workspace_exit"),
			id:'space-exit',
			icon:'ui-icon tempo-ui-icon tempo-ui-icon-delete'  
		},
//		{
//			text:TempoUtils.locale("bidesign.workspace_delete"),
//			id:'space-delete',
//			icon:'ui-icon tempo-ui-icon tempo-ui-icon-delete'  
//		}
		],
		select:function(e,ui){
		  var link = ui.linkEl;
		  var itemId = ui.select.id;
		  switch (itemId) {
		  	case 'space-enterspace':
				enterSpace(link);
				break;
		  	case 'space-default':
		  		setDefault(link);
				break;
//			case 'space-uploadcover':
//				uploadcover(link);
//				break;
		  	case 'space-exit':
				exitNode(link);
				break;
			case 'space-editmessage':
				editspace(link);
				break;
//			case 'space-delete':
//				deleteNode(link);
//				break;
			default:
				break;
			}
		  }
	});
	
	this.init = function(){
		$(".workspace-container-init").hide();
		// 初始化空间搜索框 前端搜索 已弃用
		// initWorkspaceSearchBar();
		// 重新渲染搜索结果 后端搜索
		renderSearch();
		//添加跳转notebook事件
		bindNotebookSkipButton();
		bindAddWorkspaceButton();
		ClickMangeZone();
		ClickUsedZone();
		ClickAllZone();
		listWorkSpaces();
		listAllWorkSpaces();
	}

	//渲染搜索框 后端搜索
	var renderSearch = function(){
		searchDiv.searchbar({
			//auto为true时，输入框值改变自动搜索
			//auto为false时，需点击搜索按钮进行搜索
			auto:true,
			isEnter:true,
			width:'250px',
			height:"30px",
			placeholder : "请输入工作空间名称或工作空间描述",
			//自动搜索时执行，前端搜索
			onSearch: function(text){
				searchName = text;
				listAllWorkSpaces();
			},
		})
	}

	// 初始化空间搜索框 前端搜索 已弃用
	var initWorkspaceSearchBar = function() {
		$workspaceSearchBar.searchbar({
			// auto为true时，输入框值改变自动搜索,用户输入数据1秒后搜索
			auto:true,
			width:165,
			// 输入内容提示
			placeholder:TempoUtils.locale("bidesign.workspace_search_bar"),
			//是否有删除按钮
			hasClean: true,
			onSearch: function (text) {
				// 用户输入的空间名称
				var ufdWorkspaceName = text.trim().toUpperCase();
				// 如果为空，显示全部
				if (ufdWorkspaceName.length == 0) {
					$('.workspace-list [_widgetname="workspacenode"]').show();
				}
				// 获取当前页面的所有空间名称
				var workspaceNames = $('.workspace-list [_widgetname="workspacenode"] .tempo-iconnode-item .tempo-icon-item-span-text');
				// 遍历隐藏不符合要求的空间
				var workspaceNamesLen = workspaceNames.length;
				for (var i=0; i<workspaceNamesLen; i++) {
					// 获取空间名称
					var tempName = workspaceNames[i].innerText.toUpperCase();
					// 判断是否符合要求
					if (tempName.indexOf(ufdWorkspaceName) == -1) {
						// 不符合要求将空间div进行隐藏
						$(workspaceNames[i]).parents('[_widgetname="workspacenode"]').hide();
					}else {
					    //符合要求进行显示
                        $(workspaceNames[i]).parents('[_widgetname="workspacenode"]').show();
                    }
				}
			}
		});
	}
	
	var enterSpace = function(node){
		debugger
		var workSpaceId = node.workspacenode("getData").id;
		//校验工作空间ID，防止恶意XSS攻击
		workSpaceId = checkUrlParam(workSpaceId);
		var thisUrl = contextPath + "/api/"+(fType=="mining"?"ai":"bi")+"/resource/view/theme?workSpaceId=" + workSpaceId;
		thisUrl = TempoUtils.addHideIconParam(thisUrl);
		window.location.href = thisUrl;
	}


	var checkUrlParam = function(param){
		var regExp = new RegExp(/^[0-9a-zA-z]*$/);
		var params = param.toString()
		if(regExp.test(params)){
			return params;
		}else {
			return "";
		}
	}
	
	var editspace = function(node){
		debugger
		$m.loadHtml(contextPath+"/api/ai/resource/view/workspaceDialog",$("body"),"tempo-workspace-dialog",{
			fType : fType,
			type:"edit",
			node:node,
			workSpace:node.workspacenode("getData")
		});
	}
	var setDefault = function(ui){
		if(ui.workspacenode("getData").isDefault=="true"){
			$.ajax({
				url : contextPath + ('/api/ai/workspace/revoke-default'),
				type : 'post',
				data:{fType:fType},
				dataType : 'json',
				success : function(objs) {
					$(".tempo-workspacenode").each(function(){
						$(this).workspacenode("setDefaultspace","false");
					});
					$defaultWorkspaceImg.hide();
					$defaultspace.text(TempoUtils.locale("bidesign.workspace_defaultspace"));
				} 
			});
		}else{
			var process = $("<div/>").tempoprogressbar();
			$.ajax({
				url : contextPath + ('/api/ai/workspace/grant-default'),
				type : 'post',
				data:{
					workSpaceId:ui.workspacenode("getData").id,
					fType:fType
				},
				dataType : 'json',
				success : function(objs) {
						process.tempoprogressbar("destroy");
						$(".tempo-workspacenode").each(function(){
							$(this).workspacenode("setDefaultspace","false");
						});
						ui.workspacenode("setDefaultspace","true");
						$defaultspace.text(TempoUtils.locale("bidesign.workspace_cancel_defaultspace"));
						$defaultWorkspaceImg.css({
							top:-186,
						}).show().appendTo(ui);
						$("<div/>").alert({
						msg : TempoUtils.formatText(TempoUtils.locale("bidesign.workspace_tobedefault")),
						height : 280
					});
				},
				error: function () {
					//遮罩销毁
					process.tempoprogressbar("destroy");
				}
			});
		}
	}
	
	var uploadcover = function(node){
		/**
		 * 打开封面上传对话框
		 */
		$m.loadHtml(contextPath+"/api/ai/resource/view/workspaceuploadcover",$("body"),"tempo-workspace-dialog",{
			node : node,
			type : 'uploadCover'
		});
	}
	var exitNode = function(node){
		var data = node.workspacenode("getData");
		$("<div/>").confirm({
			msg:TempoUtils.locale("bidesign.tooltip_confirm_exit"),
			ok:function() {
				var data = node.workspacenode("getData");
				if(data.isDefault == 'true'){
					setDefault(node);
				}
				exitWorkSpace(data.id,userId);
			},
			cancel:function() {
				
			}
		});
	}
	//新增工作空间按钮绑定事件
	var bindAddWorkspaceButton = function(){
		$workspaceAddButton.unbind('click').bind('click',function(){
			$m.loadHtml(contextPath+"/api/ai/resource/view/workspaceDialog",$("body"),"tempo-workspace-dialog",{
				fType : fType,
				type:"create",
				workSpace:{
					id:TempoUtils.uuid()
				}
			});
			$("#gview_tempo-workspace-permission-grid .ui-jqgrid-bdiv").css("height","140px");
//			$('.tempo-workspacenode').remove()
//			listAllWorkSpaces("create");
		});
		$workspaceInitFirstAddButton.unbind('click').bind('click',function(){
			$m.loadHtml(contextPath+"/api/ai/resource/view/workspaceDialog",$("body"),"tempo-workspace-dialog",{
				fType : fType,
				type:"create",
				workSpace:{
					id:TempoUtils.uuid()
				}
			});
			$("#gview_tempo-workspace-permission-grid .ui-jqgrid-bdiv").css("height","140px");
		});
		$workspaceInitSecondAddButton.unbind('click').bind('click',function(){
			$m.loadHtml(contextPath+"/api/ai/resource/view/workspaceDialog",$("body"),"tempo-workspace-dialog",{
				fType : fType,
				type:"create",
				workSpace:{
					id:TempoUtils.uuid()
				}
			});
			$("#gview_tempo-workspace-permission-grid .ui-jqgrid-bdiv").css("height","140px");
		});
	}

	//给NoteBook跳转按钮绑定事件
	var bindNotebookSkipButton = function() {
		$notebookSkipButton.unbind('click').bind('click', function() {
			//获取当前notebook用户的id
			var notebookUserId =$(".notebook-current-user").attr('value');
			//向NoteBook服务发起请求
			window.open("/tempo-jupyter/login?user_name=" + notebookUserId);
		});
		$notebookSkipButtonInit.unbind('click').bind('click', function() {
			//获取当前notebook用户的id
			var notebookUserId =$(".notebook-current-user").attr('value');
			//向NoteBook服务发起请求
			window.open("/tempo-jupyter/login?user_name=" + notebookUserId);
		});
	}

	/**
	 * 点击全部空间事件
	 * @constructor
	 */
	var ClickAllZone = function(){
		var _this = this;
		$zonetabsall.unbind('click').bind('click',function(){
			if (_this.lastType == 'all'){
				return;
			}
			$zonetabsall.css("color","rgb(0,0,0)");
			$zonetabsmanage.css("color","rgb(85,85,85)");
			$zonetabsused.css("color","rgb(85,85,85)");
			PriType = "";
			listAllWorkSpaces();
			_this.lastType = 'all';
		});
		//全部默认为黑色字体
		$zonetabsall.css("color","rgb(0,0,0)");
	}

	/**
	 * 点击我管理的空间事件
	 * @constructor
	 */
	var ClickMangeZone = function(){
		var _this = this;
		$zonetabsmanage.unbind('click').bind('click',function(){
			if (_this.lastType == 'mange'){
				return;
			}
			$zonetabsall.css("color","rgb(85,85,85)");
			$zonetabsmanage.css("color","rgb(0,0,0)");
			$zonetabsused.css("color","rgb(85,85,85)");
			PriType = "1";
			listAllWorkSpaces();
			_this.lastType='mange'
		});
	}

	/**
	 * 点击我参与的空间事件
	 * @constructor
	 */
	var ClickUsedZone = function(){
		var _this = this;
		$zonetabsused.unbind('click').bind('click',function(){
			if (_this.lastType == 'used'){
				return;
			}
			$zonetabsall.css("color","rgb(85,85,85)");
			$zonetabsmanage.css("color","rgb(85,85,85)");
			$zonetabsused.css("color","rgb(0,0,0)");
			PriType = "2";
			listAllWorkSpaces();
			_this.lastType='used'
		});

	}

	/**
	 * 打开工作空间对话框
	 */
	var openWorkspaceDialog  = function(type,node){
		$m.loadHtml(contextPath+"/api/ai/resource/view/workspaceDialog",$("body"),"tempo-workspace-dialog",{
			node : node,
			type : type
		});
	}

	var listWorkSpaces = function () {
		$.ajax({
			url : contextPath + ('/api/ai/workspace/list'),
			type : 'post',
			data:{
				fType:"mining",
				searchName:"",
				Type:""
			},
			async:false,
			dataType : 'json',
			success : function(result) {
				workSpaceLength = result.data.length;
			}
		});
	};

	/**
	 * 获得所有已有工程并绘制
	 */
	var listAllWorkSpaces = function(afterCreate) {
		$.ajax({
			url : contextPath + ('/api/ai/workspace/list'),
			type : 'post',
			data:{
				fType:fType,
				searchName:searchName,
				Type:PriType
			},
			async:false,
			dataType : 'json',
			success : function(result) {
				$(".tempo-workspacenode").each(function(){
					$(this).remove();
				});
				var objs = result.data;
				var lastNodeName;
				if(!objs) {
					return ;
				}else if (workSpaceLength == 0) {
					//新手引导界面
					$(".workspace-container").hide();
					$(".workspace-container-init").show();
					return;
				}else {
					$(".workspace-container").show();
					$(".workspace-container-init").hide();
				}
				objs.sort(sortRule);
				var lastNodeCreateTime=objs[0].CREATE_TIME;
				for(var i = 0; i < objs.length; i++) {
					renderNode(objs[i],'pic');
					if(objs[i].CREATE_TIME>lastNodeCreateTime){
						lastNodeCreateTime=objs[i].CREATE_TIME;
						lastNodeName=objs[i].NAME;
					}
				}
				if(afterCreate!=undefined){
					$('.tempo-icon-item-span-text').each(function(){
						if($(this).text()==lastNodeName){
							$(this).trigger('dblclick');
						}
					})
				}
			} 
		});
	}

	/**
	 * 上一个方法里使用的排序规则
	 * 比较收藏时间的前后顺序
	 * @param a 元素第n个
	 * @param b 元素第n+1个
	 * @returns {number}
	 */
	function sortRule(a,b){
		return b.NOWTIME - a.NOWTIME;
	}
	
	/**
	 * 渲染图标式节点
	 */
	var renderNode = function(obj,nodeType,orderType) {
		var div;
		var showTitle=false;
		if(orderType=='prepend'){
			div = $("<div/>").prependTo($("#workspace-list"));
		}else{
			div = $("<div/>").appendTo($("#workspace-list"));
		}
		var ntype = nodeType;
		if(nodeType=='list'){
			showTitle = true;
		}
		var type = obj.TYPE;
		var url = contextPath + "/images/default_workspace.png";
		// 处理1979-01-01 08:00:00问题
		if (obj.THUMBTIME && obj.THUMBTIME > 28800000) {
			var time = obj.THUMBTIME || obj.CREATETIME;
			url = TempoUtils.securityUrl(contextPath + "/api/ai/workspace/getThumb/"+ obj.ID + "?time=" + time);
		}
		$(div).workspacenode({
			data:{
				id:obj.ID,
				thumb:url,
				name:obj.NAME,
				userNum:obj.USERNUM,
				appNum:obj.APPNUM,
				args:obj,
				isDefault:obj.IS_DEFAULT,
				showTitle:showTitle,
				isSelf:obj.WORK_SPACE_TYPE=="self",
				descr:obj.DESCR||"暂无描述",
				nowtime:obj.NOWTIME
			},
			showDescr:true,
			showBtn:true,
			toggle:nodeType,//此处没有正常显示作者 创建时间 描述
			columnParams:[{'column':'USERNAME','title':TempoUtils.locale("bidesign.workspace_author")},{'column':'CREATETIME','title':TempoUtils.locale("bidesign.workspace_create_time")},{'column':'DESCR','title':TempoUtils.locale("bidesign.workspace_description")}],
			contextmenu:function(e,ui){
				e.preventDefault();
				e.stopPropagation();
				if(type != "1"){
					return;
				}
				var screenHeight = window.innerHeight;
				var minus = screenHeight - e.originalEvent.originalEvent.pageY;
				var menuHeight = syscontextmenu.height();
				var top = e.originalEvent.originalEvent.pageY;
				if(minus < menuHeight){
					top = e.originalEvent.originalEvent.pageY - menuHeight;
				}
				var screenWidth = window.innerWidth;
				var minuw = screenWidth - e.originalEvent.originalEvent.pageX;
				var menuWidth = syscontextmenu.width();
				var left = e.originalEvent.originalEvent.pageX;
				if(minuw < menuWidth){
					left = e.originalEvent.originalEvent.pageX;
				}
		
				syscontextmenu.contextmenu('show',{
					position:{
	   					left:left,
	   					top:top
	   				},
	   				linkEl:this
				});
			},hoverNodeImage:function(e,ui){
//				e.preventDefault();
//				e.stopPropagation();
//				$nodeItemMenu.css({
//					top:0,
//				}).show().appendTo(ui);
//				bindNodeMenuEvent(ui,obj);
			},
			tooltipContent:function(id){
				var htmls = [];
					$.ajax({
						url : contextPath + ('/api/ai/workspace/workspace-user'),
						type : 'post',
						data:{
							id: id
						},
						async:false,
						dataType : 'json',
						success : function(result) {
							var objs = result.data;
							var adminName = [];
							var userName = [];
							for(var i=0;i<objs.length;i++){
								if(objs[i].type==1){
						    		adminName.push(objs[i].name);
						    	}else{
						    		userName.push(objs[i].name);
						    	}
							}
							if(adminName.length > 20){
								adminName.length = 20;
								adminName.push("...");
							}
							if(userName.length>20){
								userName.length = 20;
								userName.push("...");
							}
							if (adminName.length > 0) {
								htmls.push(TempoUtils.formatText(TempoUtils.locale("bidesign.workspace_adminUser"))+adminName);
							}
							if (userName.length > 0) {
								htmls.push(TempoUtils.formatText(TempoUtils.locale("bidesign.workspace_user"))+userName);
							}
						} 
					});
				return htmls.join("<br/>");
		     },
			mouseleveNodeImage:function(e,ui){
//				if(!e.relatedTarget||ui[0]==e.relatedTarget){
//					return;
//				}
//				e.preventDefault();
//				e.stopPropagation();
//				$nodeItemMenu.hide();
			},
			click:function(e,ui){
				
			},
			dblclick:function(e,ui){
				e.preventDefault();   
				e.stopPropagation();
				enterSpace(ui)
			},
			btnClick:function(e,obj){
				e.preventDefault();   
				e.stopPropagation();
				changePage(e,this);
			},
			btnDblclick:function(e){
				e.stopPropagation();
			},
			//收藏点击事件
			collectClick:function(e,obj){
				e.preventDefault();
				e.stopPropagation();
				changeCollect(e,this);
			},
			collectDblclick:function(e){
				e.stopPropagation();
			},
			textDblclick : function(e) {
				e.preventDefault();
				e.stopPropagation();
				if(type != "1"){
					return;
				}
				if($(e.target).workspacenode("getData").isSelf){
					$("<div/>").alert({
						msg : TempoUtils.formatText(TempoUtils.locale("bidesign.self_workspace_not_rename")),
						height : 280
					});
					return;
				}
				var pvname =$(e.target).workspacenode("getData").name;
				var cid = $(e.target).workspacenode("getData").id;
				var cur = $(e.currentTarget);
				var node = $(e.target);
				var descr = $(e.target).workspacenode("getData").descr;
				cur.empty();
				var input = $("<input/>", {
					value : pvname,
					"class" : 'tempo-visual-pager-input tempo-visual-yahei tempo-validatebox',
				    'id':'tempo-worspace-name'
				}).appendTo(cur);
				var iconSpan=$("<span/>",{
					'class':'tempo-mark-icon tempo-exclamatory-mark',
					'id':'tempo-mark-span'
				}).css({
				 'position': 'absolute',
			     'display': 'none' ,
			     'width': '20px',
			     'margin-left':'4px',
			     'margin-top': '8px'
				}).appendTo(cur);
				
				$("#tempo-worspace-name").bind('input propertychange',function(e){
					var name=$("#tempo-worspace-name").val();
					if(name.length>60){
						$("#tempo-mark-span").show();
						$("#tempo-mark-span").css("display",'inline-block');
					}else{
						$("#tempo-mark-span").hide()
					}
				})
				$("#tempo-worspace-name").on("click dblclick", function(e) {
							e.stopPropagation();
						})
						.on("blur",function() {
							if($(this).val().trim().length<=60){
								var $thisImg = $(this).parents('a').find('img');
								$.ajax({url : contextPath + ('/api/ai/workspace/update-name'),
											data : {
												id : cid,
												name : $(this).val().trim()
											},
											type : 'post',
											dataType : 'json',
											success : $.proxy(function(result) {
												var obj = result.data;
												if (obj.status == "true") {
													node.workspacenode("setText",$(this).val().trim());
													node.workspacenode('getData').name=$(this).val().trim();
													node.workspacenode("getData").args.NAME=$(this).val().trim();
												}else{
													$("<div/>").alert({msg:TempoUtils.locale(obj.msg)});
													//还原名称
													node.workspacenode("setText",pvname);
												}
											},this)
										});
							}else{
								$("<div/>").alert({
									msg : TempoUtils.formatText(TempoUtils.locale("bidesign.workspace_name_length"), 60),
									height : 280
								});
							}
						}).focus();
						
				

			},
			textClick:function(e){
				e.preventDefault();   
				e.stopPropagation();
			},
		});
		if(obj.IS_DEFAULT=='true'){
			$defaultWorkspaceImg.css({
				top:-186,
			}).show().appendTo($(div));
		}
		
	}

	var changeCollect = function(e,ele){
		e.preventDefault();
		e.stopPropagation();
		if(!process || process.find(".tempo-tempoprogressbar").length ==0) {
			process = $("<div/>").tempoprogressbar();
			var _this = this;
			var objId = $(ele).workspacenode('getData').id;
			//当前用户Id userId
			$.ajax({
				url: contextPath + ('/api/ai/workspace/save/collectWorkSpace'),
				type: 'post',
				data: {
					objId: objId,
					userId: userId
				},
				dataType: 'json',
				success: function (objs) {
					process.tempoprogressbar("destroy");
					listAllWorkSpaces();
				},
				error: function () {
					process.tempoprogressbar("destroy");
				}
			});
		}
	}

	var changePage = function(e,ele){
		e.preventDefault();   
		e.stopPropagation();
		var screenHeight = window.innerHeight;
		var minus = screenHeight - e.pageY;
		var menuHeight = syscontextmenu.height();
		var top = e.pageY;
		if(minus < menuHeight){
			top = e.pageY - menuHeight;
		}
		var screenWidth = window.innerWidth;
		var minuw = screenWidth - e.pageX;
		var menuWidth = syscontextmenu.width();
		var left = e.pageX;
		if(minuw < menuWidth){
			left = e.pageX - menuWidth;
		}
		var defaultText =TempoUtils.locale("bidesign.workspace_cancel_defaultspace");
		var aleadyDefualt = $(ele).workspacenode("getData").isDefault=="true";
		if(!aleadyDefualt){
			defaultText = TempoUtils.locale("bidesign.workspace_defaultspace");
		}
		if($(ele).workspacenode("getData").isSelf){
			selfsyscontextmenu.contextmenu("hideItem","space-exit");
			selfsyscontextmenu.contextmenu("hideItem","space-editspace");
			selfsyscontextmenu.contextmenu("setItemText","space-default",defaultText);
			selfsyscontextmenu.contextmenu("toggle",{
				linkEl:ele,
				position:{
					left:left,
					top:top
				}
			})
		}else{
			if($(ele).workspacenode("getData").args.TYPE=='2'){
				syscontextmenu.contextmenu("showItem","space-exit");
				syscontextmenu.contextmenu("hideItem","space-editspace");
				syscontextmenu.contextmenu("hideItem","space-delete");
			}else{
				syscontextmenu.contextmenu("showItem","space-editspace");
				syscontextmenu.contextmenu("showItem","space-delete");
				syscontextmenu.contextmenu("hideItem","space-exit");
			}
			syscontextmenu.contextmenu("setItemText","space-default",defaultText);
			syscontextmenu.contextmenu("toggle",{
				linkEl:ele,
				position:{
					left:left,
					top:top
				}
			})
		}
		
	}
	var bindNodeMenuEvent = function(ui,obj){
		var aleadyDefualt = ui.workspacenode("getData").isDefault=="true";
		if(aleadyDefualt){
			$defaultspace.text(TempoUtils.locale("bidesign.workspace_cancel_defaultspace"));
		}else{
			$defaultspace.text(TempoUtils.locale("bidesign.workspace_defaultspace"));
		}
		//进入工作空间
		$enterspace.unbind('click').bind('click',function(){
			var thisUrl = contextPath + "/api/"+(fType=="mining"?"ai":"bi")+"/resource/view/theme?workSpaceId=" + obj.ID;
			thisUrl = TempoUtils.addHideIconParam(thisUrl);
			window.location.href = thisUrl;
		});
		//邀请成员
		//个人空间或只有使用权限时，不能邀请成员
		if(obj.WORK_SPACE_TYPE=="self"||obj.TYPE=="2"){
			$inviteuser.hide();
			$('.node-item-menu div').css({'marginTop':'16px'});
		}else{
			$('.node-item-menu div').css({'marginTop':'6px'});
			$inviteuser.show();
		}
		$inviteuser.unbind('click').bind('click',function(){
			if(obj.WORK_SPACE_TYPE=="self"){
				$("<div/>").alert({
					msg : TempoUtils.formatText(TempoUtils.locale("bidesign.self_workspace_not_inviteuser")),
					height : 280
				});
				return;
			}
			var dialog = $('<div>').appendTo($('body'));
			dialog.dialog({
				title:TempoUtils.locale("bidesign.workspace_inviteuser"),
				width:750,
				height:500,
				modal:true,
				resizable:false,
				open: function(){
					$m.loadHtml(contextPath+'/api/ai/workspace/view/permission',dialog,'tgeserwer',{
						workSpaceId:obj.ID
					})
				},
				buttons: [{
					text:TempoUtils.locale("bidesign.workspace_comfirm"),
					click:function(){
						editSave(dialog,obj);
					}
				},{
					text:TempoUtils.locale("bidesign.workspace_cancel"),
					click:function(){
						dialog.dialog("close");
					}
				}],
				close:function(){
					var grid = dialog.find("#tempo-workspace-permission-grid");
					var userNum = grid.datagrid('getRowData').length+1;
					ui.find(".content-button-userNum").text(userNum);
					ui.workspacenode("setUserNum",userNum);
					dialog.dialog("destroy").remove();
				}
			})
		});
		//设为默认工作空间
		$defaultspace.unbind('click').bind('click',function(){
			if(ui.workspacenode("getData").isDefault=="true"){
				$.ajax({
					url : contextPath + ('/api/ai/workspace/revoke-default'),
					type : 'post',
					data:{fType:fType},
					dataType : 'json',
					success : function(objs) {
						$(".tempo-workspacenode").each(function(){
							$(this).workspacenode("setDefaultspace","false");
						});
						$defaultWorkspaceImg.hide();
						$defaultspace.text(TempoUtils.locale("bidesign.workspace_defaultspace"));
					} 
				});
			}else{
				$.ajax({
					url : contextPath + ('/api/ai/workspace/grant-default'),
					type : 'post',
					data:{
						workSpaceId:obj.ID,
						fType:fType
					},
					dataType : 'json',
					success : function(objs) {
						$(".tempo-workspacenode").each(function(){
							$(this).workspacenode("setDefaultspace","false");
						});
						ui.workspacenode("setDefaultspace","true");
						$defaultspace.text(TempoUtils.locale("bidesign.workspace_cancel_defaultspace"));
						$defaultWorkspaceImg.css({
							top:-186,
						}).show().appendTo(ui);
						$("<div/>").alert({
						msg : TempoUtils.formatText(TempoUtils.locale("bidesign.workspace_tobedefault")),
						height : 280
					});
					} 
				});
			}
		});
		
	}
	/**
	 * 编辑人员权限后保存人员权限
	 */
	var editSave=function(dialog,obj){
		var progress = $("<div/>").tempoprogressbar();
		var grid = dialog.find("#tempo-workspace-permission-grid");
		var data = grid.datagrid('getRowData');
		if(data && data.length > 0){
			var ids = [];
			var types=[];
			for (var i = 0; i < data.length; i++) {
				ids.push(data[i].ID);
				types.push($('input[name='+data[i].TYPE.substr(data[i].TYPE.indexOf("name=")+6,36)+']:first').is(":checked")?"2":"1");
			}
			$.ajax({
				url: contextPath+"/api/ai/workspace/privis/update",
				method: 'POST',
				data: {
					ids : ids.join(','),
					types : types.join(','),
					workSpaceId:obj.ID
				},
				success: function(data) {
					progress.tempoprogressbar("destroy");
					dialog.dialog("close");
				}
			})
		}else{
			progress.tempoprogressbar("destroy");
			dialog.dialog("close");
		}
	}
	/**
	 * 右键菜单中“删除”操作绑定事件：弹出删除确认对话框
	 * 删除工作空间之前先确认工程下是否有主题，如果有主题，则不能删除。
	 */
	var deleteNode = function(node){
		if(node.workspacenode("getData").appNum>0){
			$("<div/>").alert({
				msg : TempoUtils.formatText(TempoUtils.locale("bidesign.workspace_app_not_delete")),
				height : 280
			});
			return;
		}
		var data = node.workspacenode("getData");
		$("<div/>").confirm({
			msg:TempoUtils.locale("bidesign.workspace_not_delete"),
			ok:function() {
				var data = node.workspacenode("getData");
					deleteWorkSpace(data.id, node);
			},
			cancel:function() {
				
			}
		});
	}
	
	/**
	 * 退出工程
	 */
	var exitWorkSpace = function(id,userId){
		var progress = $("<div/>").tempoprogressbar();
		$.ajax({
			url : contextPath + ('/api/ai/workspace/delete-priv-user'),
			data : {
				id:id,
				userId:userId
			},
			type : 'post',
			dataType : 'json',
			success : function(result) {
				listWorkSpaces();
				var d=result.data;
				progress.tempoprogressbar("destroy");
				if (workSpaceLength == 0) {
					//新手引导界面
					$(".workspace-container").hide();
					$(".workspace-container-init").show();
					return;
				}else {
					$(".workspace-container").show();
					$(".workspace-container-init").hide();
				}
				if (d != "error"){
					$(".tempo-workspacenode").each(function(){
						var nid = $(this).workspacenode("getData").args.ID;
						if (nid == id) {
							$(this).remove();
							return false;
						}
					});
				}
			}
		});
	}
	/**
	 * 删除一个工程
	 */
	var deleteWorkSpace = function(id) {
		var progress = $("<div/>").tempoprogressbar();
		$.ajax({
			url : contextPath + ('/api/ai/workspace/delete'),
			data : {
				id:id
			},
			type : 'post',
			dataType : 'json',
			success : function(result) {
				listWorkSpaces();
				var id=result.data;
				progress.tempoprogressbar("destroy");
				if (id != "error"){
					$(".tempo-workspacenode").each(function(){
						var nid = $(this).workspacenode("getData").args.ID;
						if (nid == id) {
							$(this).remove();
							return false;
						}
					});
					if (workSpaceLength == 0){
						//新手引导界面
						$(".workspace-container").hide();
						$(".workspace-container-init").show();
						return;
					}else {
						$(".workspace-container").show();
						$(".workspace-container-init").hide();
					}
				}
			}
		});
	}
}

$(function() {
	var biWorksapce = new BiWorksapce();
	biWorksapce.init();
});